import time
from datetime import datetime
from opcua import Client
import threading
import tkinter as tk
from tkinter import ttk

class ConnectRob(threading.Thread):
    def __init__(self,server_urls):
        super().__init__()
        self.IP=server_urls        
        self.btag=False
        self.Var_Mem=False
        self.Picknum=0
        self.Errnum=0
        self.start_time=0
        self.NullPlateMass=0
        url = f"opc.tcp://{self.IP}:4840/"
        username = "OpcUaOperator"
        password = "kuka"
        self.client = Client(url)
        self.client.set_user(username)
        self.client.set_password(password)
        

    def Readnodes(self):
        node_infos = []
        with open("nodes.txt", "r") as file:
            lines = file.readlines()    
        for line in lines:
            node_infos.append(line.strip())
        return [self.client.get_node(node_info) for node_info in node_infos]
    
    def ris(self,bVar):
        if bVar and (bVar!=self.btag):
            tagretun=True
        else:
            tagretun=False
        self.btag=bVar
        return tagretun
    
    def Var_FP(self,bVar):
        Var_FP=bVar and not self.Var_Mem
        self.Var_Mem=Var_FP
        return Var_FP
    def update_table(self):
        # 清空表格
        for item in self.listbox.get_children():
            self.listbox.delete(item)

        # 根据变量值更新表格数据
        for node in self.nodes:
            self.listbox.insert("", "end", values=(node.get_display_name().Text,node.get_value()))
        self.listbox.insert("","end",values=("Picknum",self.Picknum))
        self.listbox.insert("","end",values=("Errnum",self.Errnum))
        self.window.after(10,self.update_table)

    def CreatWindows(self):
        self.window = tk.Tk()
        self.window.title(self.IP)
        self.listbox = ttk.Treeview(self.window, columns=("列1", "列2"), show="headings",height=400)
        self.listbox.heading("列1", text="变量名称")
        self.listbox.heading("列2", text="变量值")
        
        self.update_table()    
        # 使用grid布局管理器
        self.listbox.grid(row=0, column=0, sticky="nsew")
        # 设置行和列的权重
        self.window.grid_rowconfigure(0, weight=1)
        self.window.grid_columnconfigure(0, weight=1)
        self.window.mainloop()

    def MonitorVar(self):
        self.CreatWindows()
        while True:
            bigripareaFp=self.Var_FP(self.nodes[1].get_value())
            if self.nodes[1].get_value():
                self.NullPlateMass=self.nodes[24].get_value()
            if bigripareaFp:
                self.start_time=time.time()
                self.Picknum=self.Picknum+1
                print(f"{self.client.server_url}在监控时间内已抓{self.Picknum}片",datetime.now().strftime("%H:%M:%S %Y-%m-%d"))
                print("-" * 50)
            elapsed_time=time.time()-self.start_time
            if self.nodes[24].get_value()==self.NullPlateMass and self.nodes[23]==False and elapsed_time>2:
                self.Errnum=self.Errnum+1
                print(f"{self.client.server_url}在监控时间内已抓{self.Errnum}片",datetime.now().strftime("%H:%M:%S %Y-%m-%d"))
                print("-" * 50)

    def run(self):
        try:
            print(f"\n开始连接{self.IP}")
            self.client.connect()
            print("\n连接成功！")

        except Exception as e:
            print("连接失败：", e)
        self.nodes=self.Readnodes()
        self.MonitorVar()

    def _del_(self):
        self.client.disconnect()
        print(f"{self.client.server_url}已断开与服务器的连接。")

while True:
    RobIP = input("\n请输入需要监控的机器人IP:")
    Rob_t = ConnectRob(RobIP)
    Rob_t.start()